package com.wosai.teach.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.activeandroid.Model;
import com.activeandroid.query.Select;
import com.wosai.teach.pojo.Experiment;

public class ExperimentDao extends BaseDao {

	public ExperimentDao() {
		this.initForm();
	}

	public void initForm() {
		from = new Select().from(Experiment.class);
	}

	public void saveOrUpdate(Experiment experiment) {
		Experiment db_exp = this.getExperimentByExpId(experiment.getExpId());
		if (db_exp == null || db_exp.getExpId() != experiment.getExpId()) {
			experiment.save();
		} else {
			if (db_exp.getApkVer() <= experiment.getApkVer()) {
				// 需要更新
				db_exp.setApkClassName(experiment.getApkClassName());
				db_exp.setApkPackageName(experiment.getApkPackageName());
				db_exp.setApkURL(experiment.getApkURL());
				db_exp.setApkVer(experiment.getApkVer());
				db_exp.setApkSize(experiment.getApkSize());
				db_exp.setIcon1(experiment.getIcon1());
				db_exp.setTmApkUpdate(experiment.getTmApkUpdate());
				db_exp.setKeywords(experiment.getKeywords());
				db_exp.save();
			}
		}
	}

	public void saveOrUpdateExp(Experiment exp) {
		Experiment db_exp = this.getExperimentByExpId(exp.getExpId());
		if (db_exp != null) {
			exp.corpModel(db_exp);
		}
		this.initForm();
		exp.save();
	}

	public Experiment getExperimentByExpId(Integer expId) {
		this.initForm();
		from.where("expId = ?", expId);
		Experiment experiment = from.executeSingle();
		return experiment;
	}

	/**
	 * 清理服务器不存在的数据
	 * 
	 * @param expIdList
	 */
	public void clearExperimentByExpId(List<Integer> expIdList) {
		List<Experiment> modelList = findAllExperiment();
		if (modelList == null || modelList.isEmpty() || expIdList == null
				|| expIdList.isEmpty()) {
			return;
		}
		for (Experiment exp : modelList) {
			if (!expIdList.contains(exp.getExpId())) {
				exp.delete();
			}
		}
	}

	/**
	 * 删除所有数据
	 */
	public void deleteAllDb() {
		List<Model> modelList = this.findAll();
		for (Model model : modelList) {
			model.delete();
		}
	}

	public List<Experiment> findAllExperiment() {
		List<Experiment> allList = new ArrayList<Experiment>();
		List<Model> modelList = findAll();
		if (modelList == null || modelList.isEmpty()) {
			return null;
		}
		// TODO 位置原因，需要去重复
		Map<Integer, Integer> ids = new HashMap<Integer, Integer>();
		for (Model model : modelList) {

			Experiment all = (Experiment) model;
			if (ids.containsKey(all.getExpId())) {
				all.delete();
				continue;
			}
			ids.put(all.getExpId(), all.getExpId());
			allList.add(all);
		}
		return allList;
	}
}
